package com.sankuai.project.controller;

import com.sankuai.project.annotation.LogAnnotation;
import com.sankuai.project.model.User;
import com.sankuai.project.service.BatchRunRedisUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@RestController
public class loginController {

    private final static int NUMBER = 100000;

    @Resource
    private RedisTemplate stringRedisTemplate;

    @Resource
    private BatchRunRedisUtil batchRunRedisUtil;

    @LogAnnotation
    @PostMapping("/login")
    public String login(@RequestBody User user) {
        System.out.println(user);
        return "hello world login success";
    }

    @PostMapping("/add/{num}")
    public String add(@PathVariable Integer num) {
        System.out.println("传入的参数num = " + num);
        return "add success";
    }

    @RequestMapping(value = "redis")
    @ResponseBody
    public String testRedis() {
        //for循环批量添加
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < NUMBER; i++) {
            stringRedisTemplate.opsForValue().set("aaa" + i, "a", 60);
        }

        long endTime = System.currentTimeMillis();
        System.out.println("普通set消耗" + (endTime - startTime) + "毫秒");

        //利用pipeline批量操作
        long startTime2 = System.currentTimeMillis();
        Map map = new HashMap(NUMBER);
        for (int i = 0; i < NUMBER; i++) {
            map.put("bbb" + i, "b");
        }
        batchRunRedisUtil.batchSetOrExpire(map, 60L);
        long endTime2 = System.currentTimeMillis();
        System.out.println("管道set消耗" + (endTime2 - startTime2) + "毫秒");

        //multiSet()批量操作
        long startTime3 = System.currentTimeMillis();
        Map map2 = new HashMap(NUMBER);
        for (int i = 0; i < NUMBER; i++) {
            map2.put("ccc" + i, "b");
        }
        batchRunRedisUtil.batchSet(map2);
        long endTime3 = System.currentTimeMillis();
        System.out.println("批量set消耗" + (endTime3 - startTime3) + "毫秒");
        return "OK";
    }

}
